package org.cheetah.core;

import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import org.cheetah.core.action.spi.ExpressionDefinition;
import org.cheetah.core.action.spi.ForkDefinition;
import org.cheetah.core.action.spi.FromDefinition;
import org.cheetah.core.action.spi.IfDefinition;
import org.cheetah.core.action.spi.PipelineDefinition;
import org.cheetah.core.action.spi.SwitchDefinition;
import org.cheetah.core.action.spi.ToDefinition;
import org.cheetah.core.util.JAXBUtils;
import org.cheetah.core.util.ResourceUtils;

public abstract class ServiceBuilder {
	public static void loadXML(String location) throws Exception {
		URL[] urls = ResourceUtils.getURLs(location);
		List<Object> registered = new ArrayList<Object>();

		for (int i = 0; i < urls.length; ++i) {
			Object obj;

			try {
				obj = JAXBUtils.unmarshal(urls[i]);
			} catch (Throwable t) {
				t.printStackTrace();
				continue;
			}

			if (obj instanceof ServiceDefinition) {
				registered.add(((ServiceDefinition) obj).register());
			} else if (obj instanceof ServiceContextDefinition) {
				registered.add(((ServiceContextDefinition) obj).register());
			}
		}

		for (Object obj : registered) {
			if (obj instanceof ServiceDefinition) {
				((ServiceDefinition) obj).start();
			} else if (obj instanceof ServiceContextDefinition) {
				((ServiceContextDefinition) obj).start();
			}
		}
	}

	public static ServiceDefinition service(String name) {
		return new ServiceDefinition().setName(name);
	}

	public static ExpressionDefinition expression(String language,
			String expression) {
		return new ExpressionDefinition().expression(language, expression);
	}

	public static ForkDefinition fork() {
		return new ForkDefinition();
	}

	public static FromDefinition from(String uri) {
		return new FromDefinition().uri(uri);
	}

	public static IfDefinition condition(ExpressionDefinition expression) {
		return new IfDefinition().condition(expression);
	}

	public static PipelineDefinition pipeline() {
		return new PipelineDefinition();
	}

	public static SwitchDefinition _switch() {
		return new SwitchDefinition();
	}

	public static ToDefinition to(String uri) {
		return new ToDefinition().uri(uri);
	}
}
